import dealer_level_change from './dealer_level_change'

export default function (sqlite) {
  return {
    // 抽离插入逻辑
    executeInsert(resolve, reject, params) {
      const sql = `
        INSERT INTO dealer 
        (parent_dealer_id, parent_dealer_name, dealer_level_id, dealer_level_name, dealer_name, dealer_address, dealer_mobile, dealer_remark,is_delete)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?,0)
      `
      sqlite.run(sql, params, function (err) {
        if (err) {
          console.error('Error inserting dealer:', err.message)
          reject('Error inserting dealer')
        } else {
          resolve(this.lastID) // 返回新插入记录的ID
        }
      })
    },
    // 插入经销商
    insertDealer(
      parentDealerId,
      parentDealerName,
      dealerLevelId,
      dealerLevelName,
      dealerName,
      dealerAddress,
      dealerMobile,
      dealerRemark
    ) {
      return new Promise((resolve, reject) => {
        // 检查 dealer_name 是否已存在
        const checkNameSql =
          'SELECT COUNT(*) as count FROM dealer WHERE dealer_name = ? AND is_delete!=1'
        sqlite.get(checkNameSql, [dealerName], (nameErr, nameRow) => {
          if (nameErr) {
            console.error('Error checking dealer_name:', nameErr.message)
            reject('Error checking dealer_name')
          } else if (nameRow.count > 0) {
            // 如果 dealer_name 已存在
            resolve('名称重复')
          } else {
            // 如果 `parent_dealer_id` 为空值，检查是否已有记录存在
            if (!parentDealerId) {
              const checkParentSql =
                'SELECT COUNT(*) as count FROM dealer WHERE parent_dealer_id IS NULL OR parent_dealer_id = 0'
              sqlite.get(checkParentSql, [], (parentErr, parentRow) => {
                if (parentErr) {
                  console.error('Error checking parent_dealer_id:', parentErr.message)
                  reject('Error checking parent_dealer_id')
                } else if (parentRow.count > 0) {
                  // 如果已有 parent_dealer_id 为空的数据
                  resolve('仅允许一条顶级经销商记录')
                } else {
                  // 插入新的 dealer 记录
                  this.executeInsert(resolve, reject, [
                    parentDealerId,
                    parentDealerName,
                    dealerLevelId,
                    dealerLevelName,
                    dealerName,
                    dealerAddress,
                    dealerMobile,
                    dealerRemark
                  ])
                }
              })
            } else {
              // 插入新的 dealer 记录
              this.executeInsert(resolve, reject, [
                parentDealerId,
                parentDealerName,
                dealerLevelId,
                dealerLevelName,
                dealerName,
                dealerAddress,
                dealerMobile,
                dealerRemark
              ])
            }
          }
        })
      })
    },
    // 更新经销商信息
    updateDealer(
      dealerId,
      parentDealerId,
      parentDealerName,
      dealerLevelId,
      dealerLevelName,
      dealerName,
      dealerAddress,
      dealerMobile,
      dealerRemark
    ) {
      return new Promise((resolve, reject) => {
        // 查询当前的 dealer_level_id
        const getCurrentLevelSql = 'SELECT dealer_level_id FROM dealer WHERE dealer_id = ?'
        sqlite.get(getCurrentLevelSql, [dealerId], (err, row) => {
          if (err) {
            console.error('Error fetching current dealer_level_id:', err.message)
            reject('Error fetching current dealer_level_id')
          } else {
            const currentDealerLevelId = row.dealer_level_id // 当前的 dealer_level_id

            // 检查是否存在相同的 dealer_name，忽略当前 dealer
            const checkSql =
              'SELECT COUNT(*) AS count FROM dealer WHERE dealer_name = ? AND dealer_id != ? AND is_delete!=1'
            sqlite.get(checkSql, [dealerName, dealerId], (err, row) => {
              if (err) {
                console.error('Error checking dealer_name:', err.message)
                reject('Error checking dealer_name')
              } else if (row.count > 0) {
                // 如果 dealer_name 已存在，返回提示信息
                resolve('名称重复')
              } else {
                // 如果 parent_dealer_id 为 null 或 0，检查是否已有记录满足此条件
                if (!parentDealerId) {
                  const parentCheckSql = `
                    SELECT COUNT(*) AS count
                    FROM dealer
                    WHERE (parent_dealer_id IS NULL OR parent_dealer_id = 0) AND dealer_id != ?
                  `
                  sqlite.get(parentCheckSql, [dealerId], (err, row) => {
                    if (err) {
                      console.error('Error checking parent_dealer_id:', err.message)
                      reject('Error checking parent_dealer_id')
                    } else if (row.count > 0) {
                      // 已存在 parent_dealer_id 为 null 或 0 的记录，返回提示信息
                      resolve('仅允许一条顶级经销商记录')
                    } else {
                      // 执行更新操作
                      performUpdate(currentDealerLevelId)
                    }
                  })
                } else {
                  // 执行更新操作
                  performUpdate(currentDealerLevelId)
                }
              }
            })
          }
        })

        // 更新操作封装在一个函数中，避免重复代码
        const performUpdate = (currentDealerLevelId) => {
          const updateSql = `
            UPDATE dealer
            SET parent_dealer_id = ?, parent_dealer_name = ?, dealer_level_id = ?,
                dealer_level_name = ?, dealer_name = ?, dealer_address = ?,
                dealer_mobile = ?, dealer_remark = ?
            WHERE dealer_id = ?
          `
          sqlite.run(
            updateSql,
            [
              parentDealerId,
              parentDealerName,
              dealerLevelId,
              dealerLevelName,
              dealerName,
              dealerAddress,
              dealerMobile,
              dealerRemark,
              dealerId
            ],
            function (err) {
              if (err) {
                console.error('Error updating dealer:', err.message)
                reject('Error updating dealer')
              } else {
                if (currentDealerLevelId !== dealerLevelId) {
                  // 如果 dealer_level_id 发生变化，调用 changeLevel 方法
                  dealer_level_change(sqlite).insertDealerLevelChange(dealerId, dealerName)
                }
                resolve(this.changes > 0) // 返回更新操作是否影响了行数
              }
            }
          )
        }
      })
    },

    // 获取经销商
    getDealerList(pageSize, offset, dealerLevelId = null, dealerName = null) {
      return new Promise((resolve, reject) => {
        // 基础查询条件
        let baseSql = 'FROM dealer WHERE is_delete=0'
        const params = []

        // 添加 dealer_level_id 精确查询条件（如果提供）
        if (dealerLevelId) {
          baseSql += ' AND dealer_level_id = ?'
          params.push(dealerLevelId)
        }

        // 添加 dealer_name 模糊查询条件（如果提供）
        if (dealerName) {
          baseSql += ' AND dealer_name LIKE ?'
          params.push(`%${dealerName}%`)
        }

        // 构建获取总数的查询
        const countSql = `SELECT COUNT(*) as total ${baseSql}`

        // 构建分页查询
        const dataSql = `SELECT * ${baseSql} ORDER BY create_time DESC LIMIT ? OFFSET ?`
        const dataParams = [...params, pageSize, offset] // 分页参数

        // 执行两个查询：一个统计总数，一个获取分页数据
        sqlite.get(countSql, params, (err, countRow) => {
          if (err) {
            console.error('Error counting dealer records:', err.message)
            reject(err.message)
          } else {
            const total = countRow.total

            // 查询实际数据
            sqlite.all(dataSql, dataParams, (err, rows) => {
              if (err) {
                console.error('Error fetching dealer data:', err.message)
                reject(err.message)
              } else {
                resolve({ total, rows })
              }
            })
          }
        })
      })
    },

    // 获取经销商总数
    getDealerListCount(dealerId = null) {
      return new Promise((resolve, reject) => {
        let sql
        const params = []

        if (dealerId) {
          // 使用递归查询找到所有层级的子集，并包含自己
          sql = `
            WITH RECURSIVE sub_dealers AS (
              SELECT dealer_id FROM dealer WHERE dealer_id = ? AND is_delete=0  -- 包含自身
              UNION ALL
              SELECT d.dealer_id FROM dealer d
              INNER JOIN sub_dealers sd ON d.parent_dealer_id = sd.dealer_id
            )
            SELECT COUNT(1) AS count FROM sub_dealers
          `
          params.push(dealerId)
        } else {
          // 没有传入 dealerId 时查询所有记录的总数
          sql = 'SELECT COUNT(1) AS count FROM dealer where is_delete=0'
        }

        sqlite.all(sql, params, (err, rows) => {
          if (err) {
            console.error('Error in getDealerListCount:', err.message)
            reject(err.message)
          } else {
            // 返回计数
            resolve(rows[0].count)
          }
        })
      })
    },

    // 调整经销商等级
    updateDealerLevel(dealerLevelId, dealerLevelName, dealerId) {
      return new Promise((resolve, reject) => {
        const sql = 'UPDATE dealer SET dealer_level_id=?,dealer_level_name=? WHERE dealer_id=?'
        sqlite.run(sql, [dealerLevelId, dealerLevelName, dealerId], (err, rows) => {
          if (err) {
            console.error('Error updateDealerLevel:', err.message)
            reject(err.message)
          } else {
            resolve(this.changes > 0)
          }
        })
      })
    },

    // 修改备注
    updateDealerRemark(dealerRemark, dealerId) {
      return new Promise((resolve, reject) => {
        const sql = 'UPDATE dealer SET dealer_remark=? WHERE dealer_id=?'
        sqlite.run(sql, [dealerRemark, dealerId], (err, rows) => {
          if (err) {
            console.error('Error updateDealerRemark:', err.message)
            reject(err.message)
          } else {
            resolve(this.changes > 0)
          }
        })
      })
    },

    // 删除经销商
    deleteDealer(dealerId, parentId, parentName) {
      return new Promise((resolve, reject) => {
        // 更新子经销商的 parent_dealer_id 和 parent_dealer_name
        const updateSql =
          'UPDATE dealer SET parent_dealer_id = ?, parent_dealer_name = ? WHERE parent_dealer_id = ?'

        sqlite.run(updateSql, [parentId, parentName, dealerId], (updateErr) => {
          if (updateErr) {
            console.error('Error updating child dealers:', updateErr.message)
            reject('Error updating child dealers')
          } else {
            // 删除目标经销商
            const deleteSql = 'UPDATE dealer SET is_delete=1 WHERE dealer_id = ?'

            sqlite.run(deleteSql, [dealerId], function (deleteErr) {
              if (deleteErr) {
                console.error('Error deleting dealer:', deleteErr.message)
                reject('Error deleting dealer')
              } else {
                resolve(this.changes > 0)
              }
            })
          }
        })
      })
    },
    // 获取所有经销商
    getDealerAll(dealerLevelId = null, dealerName = null) {
      return new Promise((resolve, reject) => {
        // 基础查询条件
        let baseSql = 'FROM dealer WHERE is_delete=0'
        const params = []

        // 添加 dealer_level_id 精确查询条件（如果提供）
        if (dealerLevelId) {
          baseSql += ' AND dealer_level_id = ?'
          params.push(dealerLevelId)
        }

        // 添加 dealer_name 模糊查询条件（如果提供）
        if (dealerName) {
          baseSql += ' AND dealer_name LIKE ?'
          params.push(`%${dealerName}%`)
        }
        // 构建分页查询
        const dataSql = `SELECT * ${baseSql} ORDER BY create_time ASC`
        const dataParams = [...params] // 分页参数
        // 查询实际数据
        sqlite.all(dataSql, dataParams, (err, rows) => {
          if (err) {
            console.error('Error getDealerAll data:', err.message)
            reject(err.message)
          } else {
            resolve({ rows })
          }
        })
      })
    }
  }
}
